package so.shanku.essential.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import com.alipay.android.msp.demo.Keys;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.download.DownLoadQueue;
import net.tsz.afinal.download.DownloadService;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import net.tsz.afinal.sdcard.SdcardHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseActivity;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.Utils;
import so.shanku.essential.view.WihteRoundCornersDialog;

import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2015/8/17 0017.
 */
public class SplashActivity extends BaseActivity implements ServiceConnection {

    @ViewInject(id = R.id.logo_msg_iv)
    private ImageView logo_msg_iv;
    @ViewInject(id = R.id.essential_logo_iv)
    private ImageView essential_logo_iv;
    @ViewInject(id = R.id.splash_line_iv)
    private ImageView splash_line_iv;
    // 等待网络请求个数
    private int isCanNextActivity = 3;
    private boolean boolStartAnimation = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_activity_layout);
        String string=""+System.currentTimeMillis();

//        if (Utils.isHasLogin(mContext)) {
//            isCanNextActivity = 3;
//            getData_UserBrand(false);
//        } else {
//            isCanNextActivity = 2;
//        }

        isCanNextActivity = 1;
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        float density = metric.density;  // 屏幕密度（0.75 / 1.0 / 1.5）

        myApplication.setScreenWidth(width);
        myApplication.setScreenHeight(height);
        myApplication.setScreenDensity(density);

        // 设置列表每页加载数量
//        Intent e = new Intent(this, DownloadService.class);
//        this.startService(e);
//        this.bindService(e, this, BIND_AUTO_CREATE);
//        upversion();
       // next();

    }


    @Override
    protected void onResume() {
        super.onResume();
//        if (boolStartAnimation) {
//            boolStartAnimation = false;
//            startAnimation();
//        }
        jumpToNextOrSetCanJump();
    }

    Animation animin;
    Animation animAlphaIn;

    private void startAnimation() {
        Animation animout = AnimationUtils.loadAnimation(this, R.anim.zoom_exit);
        animAlphaIn = AnimationUtils.loadAnimation(this, R.anim.alpha_in);
        animin = AnimationUtils.loadAnimation(this, R.anim.zoom_enter);
        essential_logo_iv.startAnimation(animout);
        animout.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                animAlphaIn.cancel();
                animin.cancel();
                splash_line_iv.setVisibility(View.GONE);
                logo_msg_iv.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                startNextAnimation();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        // startNextAnimation();
        animin.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                jumpToNextOrSetCanJump();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void startNextAnimation() {
        essential_logo_iv.setVisibility(View.GONE);
        logo_msg_iv.setVisibility(View.VISIBLE);
        splash_line_iv.startAnimation(animin);
        logo_msg_iv.startAnimation(animAlphaIn);
        splash_line_iv.setVisibility(View.VISIBLE);
    }

    /**
     * 关注品牌接口
     */
    private void getData_UserBrand(boolean chearAllData) {

//        Map<String, Object> params = new HashMap<String, Object>();
//
//        params.put("currentPage", 1);
//        params.put("pageSize", 10000); //不分页请求
//        params.put("UserInfoId", Utils.getUserId(this));
//        GetDataQueue queue = new GetDataQueue();
//        queue.setCallBack(callBackAttentionBrandCallback);
//        queue.setActionName(GetDataConfing.GetAction_GetFocusVendorVO);
//        queue.setWhat(GetDataConfing.what_GetFocusVendorVO);
//        queue.setParamsNoJson(params);
//        getDataUtil.getData(queue);
        jumpToNextOrSetCanJump();
    }


    /**
     * 进入本界面停留2秒后做的事情
     */
    private void next() {
        if (SdcardHelper.ExistSDCard()) {
            File downLoadDir = new File(Constant.productPath);
            if (!downLoadDir.exists()) {// 判断文件是否存在，不存在就创建
                downLoadDir.mkdir();
            }
        }
        // String ip = "http://appservice.budayang.com";
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_GetConfigInfo);
        queue.setParams(new HashMap<String, String>());
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetConfigInfo);
        getDataUtil.getData(queue);
        // goMainActivity();
    }

    /**
     * 检测版本
     */
    private void upversion() {
        if (!net.tsz.afinal.sdcard.SdcardHelper.ExistSDCard()) {
            toast.showToast(R.string.nosdcard);
            jumpToNextOrSetCanJump();
        } else {
            GetDataQueue queue = new GetDataQueue();
            queue.setActionName(GetDataConfing.Action_selectAppVersionInfo);
            queue.setParams(new HashMap<String, String>());
            queue.setCallBack(callBack);
            queue.setWhat(GetDataConfing.What_selectAppVersionInfo);
            getDataUtil.getData(queue);
        }

    }

    /**
     * 提示用户有新版本
     */
    /**
     * 提示用户有新版本
     */
    String apkDownLoadPath;
    WihteRoundCornersDialog builder;

    /**
     * 提示用户有新版本
     */
    private void showNewVersion(JsonMap<String, Object> info) {
        apkDownLoadPath = info.getStringNoNull("VersionPath");
        builder = new WihteRoundCornersDialog(mContext,
                R.style.ExitDialogStyle, 2, callBackdialog1);
        builder.setTitletext(R.string.app_version_select);
        builder.setMessagetext(info.getStringNoNull("Description"));
        builder.setButtonText(R.string.app_version_iknow, R.string.app_version_update);
        builder.show();
    }

    private WihteRoundCornersDialog.DialogCallBack callBackdialog1 = new WihteRoundCornersDialog.DialogCallBack() {

        @Override
        public void bttonclick(int index) {
            builder.dismiss();
            switch (index) {
                case 1:

                    break;
                case 2:
                    String appName = getString(R.string.app_name);
                    startDownload(apkDownLoadPath,appName+".apk",appName,1);

                    break;
                default:
                    break;
            }
        }

        @Override
        public void bttonclick(int index, int what) {

        }

    };


    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
                    if (entity.what == GetDataConfing.What_selectAppVersionInfo) {

                        List<JsonMap<String, Object>> infoData = JsonParseHelper
                                .getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        if (infoData.size() == 0) {
                            jumpToNextOrSetCanJump();
                        } else {
                            JsonMap<String, Object> info = infoData.get(0);
                            if (info.getStringNoNull("VersionNo").equals(myApplication.getVersionName())
                                    || "".equals(info.getStringNoNull("VersionNo"))
                                    || "".equals(info.getStringNoNull("VersionPath"))) {
                                jumpToNextOrSetCanJump();
                            } else {
                                showNewVersion(info);
                            }
                        }
                    } else if (entity.what == GetDataConfing.What_GetConfigInfo) {
                        List<JsonMap<String, Object>> info = JsonParseHelper
                                .getJsonMap_List_JsonMap(entity.getInfo(),
                                        JsonKeys.Key_Info);
                        initPayData(info);
                        jumpToNextOrSetCanJump();
                    }
                } else {
                    jumpToNextOrSetCanJump();
                }
            } else {
                jumpToNextOrSetCanJump();
            }

        }

    };

    /**
     * 配置支付信息
     *
     * @param info
     */
    private void initPayData(List<JsonMap<String, Object>> info) {
        if (info.size() == 0) {
        } else {
            JsonMap<String, Object> config = info.get(0);
            Keys.DEFAULT_PARTNER = config
                    .getStringNoNull("PartnerID");
            Keys.DEFAULT_SELLER = config
                    .getStringNoNull("SellerNo");
            Keys.PRIVATE = config
                    .getStringNoNull("PrivateKey");
            Keys.PUBLIC = config
                    .getStringNoNull("AlipayPublicKey");
            Keys.URL = config
                    .getStringNoNull("NotifyUrl");


            /**
             * 微信支付
             */
            Keys.WeiXinPaySignKey = config
                    .getStringNoNull("WeiXinPaySignKey");
            Keys.WeiXinPartnerId = config
                    .getStringNoNull("WeiXinPartnerId");

            Keys.WeiXinPartnerKey = config
                    .getStringNoNull("WeiXinPartnerKey");
            Keys.WeiXinNotifyUrl = config
                    .getStringNoNull("WeiXinNotifyUrl");

        }
    }

    private void jumpToNextOrSetCanJump() {
        isCanNextActivity--;
        if (isCanNextActivity <= 0) {
            jumpTo(MainActivity.class, true);
//            if (!Utils.isHasLogin(this)) { //是否已登录  访客登录视为不登录
//                Intent intentLogin = new Intent(this, NoLoginActivity.class);
//                intentLogin.putExtra(ExtraKeys.Key_Msg1, 0);
//                jumpTo(intentLogin, true);
//
//            } else {
//                jumpTo(MainActivity.class, true);
//                //getGoodsReturn("O73710277232805",null);
//            }
        } else {
        }
    }


    private DownloadService.DownloadServiceBinder binder;

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        this.binder = (DownloadService.DownloadServiceBinder) service;
//        if(!this.isToStop) {
//            this.queue = this.binder.getService().addQueue(this.queue);
//        }
    }
    private DownLoadQueue queue;

    private void startDownload(String url, String fileName, String title, int id) {
        this.queue = new DownLoadQueue();
        this.queue.setId(id);
        this.queue.setIconResId(R.drawable.app_icon);
        this.queue.setCancel(false);
        this.queue.setDownLoadedPath(Constant.productPath + fileName);
        this.queue.setDownLoadUrl(url);
        this.queue.setName(title);
        this.queue.setOpenFileType("application/vnd.android.package-archive");
        this.queue.setDownLoadedAutoOpenFile(true, "application/vnd.android.package-archive");//自动打开app

        binder.getService().addQueue(this.queue);

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    @Override
    protected void onDestroy() {
        //unbindService(this);
        super.onDestroy();
    }
}